package cn.com.cetccst.uicomponents.binding.app;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

public abstract class DataBindingDialog<V extends ViewDataBinding> extends Dialog {

    private V binding;

    protected abstract void initViewModel();

    protected abstract DataBindingConfig getDataBindingConfig();

    public DataBindingDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViewModel();

        DataBindingConfig dataBindingConfig = getDataBindingConfig();
        if (dataBindingConfig != null && dataBindingConfig.getLayout() > 0) {

            V binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()),
                    dataBindingConfig.getLayout(), null, false);

            setContentView(binding.getRoot());

            getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            getWindow().setGravity(Gravity.CENTER);

            if (dataBindingConfig.getStateViewModel() != null) {
                binding.setVariable(dataBindingConfig.getVmVariableId(), dataBindingConfig.getStateViewModel());
            }
            SparseArray bindingParams = dataBindingConfig.getBindingParams();
            for (int i = 0, length = bindingParams.size(); i < length; i++) {
                binding.setVariable(bindingParams.keyAt(i), bindingParams.valueAt(i));
            }
            this.binding = binding;
        }
    }

    public V getBinding() {
        return binding;
    }

}
